package com.three.usermanagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.three.core.entity.Role;
import com.three.core.vo.R;
import com.three.usermanagement.mapper.RoleMapper;
import com.three.usermanagement.service.RoleService;
import com.three.usermanagement.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Override
    public R<Page<Role>> selectRoleByPage(RoleVo roleVo) {
        QueryWrapper<Role> queryWrapper=new QueryWrapper<>();
        if(roleVo.getRoleName()!=null){
            queryWrapper.like("role_name",roleVo.getRoleName());
        }
        queryWrapper.eq("del_flag",0);
        Page<Role> page = new Page<>(roleVo.getCurrentPage(), roleVo.getPageSize());
        Page<Role> rolePage = roleMapper.selectPage(page, queryWrapper);
        return new R<Page<Role>>(200,"查询成功",rolePage);
    }

    @Override
    public R selectUserRole(Integer id) {
        List<Role> roles = roleMapper.selectRoleByUserId(id);
        return new R(200,"查询成功",roles);
    }

    @Override
    public R updateRole(Integer userId, Integer[] roleIds) {
        // 先删除用户的所拥有角色
        int deleteCount = roleMapper.deleteRolesByUserId(userId);
        if (deleteCount < 0) {
            return new R(500, "删除旧角色失败", null);
        }
        // 如果新的角色数组不为空，则添加新的角色
        if (roleIds != null && roleIds.length > 0) {
            int insertCount = roleMapper.batchInsert(userId, roleIds);
            if (insertCount <= 0) {
                return new R(500, "授权失败", null);
            }
        }
        return new R(200, "授权成功", null);
    }

    @Override
    public R deleteRoleById(Integer roleId) {
        int i = roleMapper.deleteRoleById(roleId);
        if (i > 0) {
            return new R(200, "删除成功", null);
        } else {
            return new R(500, "删除失败", null);
        }
    }
}
